<template>
  <div
    :title="view === 'create'? '新增': '编辑'"
    :visible="true"
    class="dialogWrapper"
    :before-close="closeDialog"
    >
    <el-button type="primary" @click="closeDialog" class="retu">返回</el-button>
    <el-form :model="formData" label-width="80px" ref="ruleForm" :rules="rules">
     <!-- <el-form-item label="栏目id" prop="id" required v-if="view === 'edit'">
        <el-input v-model="formData.id" disabled></el-input>
      </el-form-item> -->
      <el-form-item label="站点id" prop="siteId" required>
        <el-input v-model="formData.siteId"></el-input>
      </el-form-item>
      <el-form-item label="上级栏目" prop="parentId" >
        <el-input v-model="formData.parentId"></el-input>
      </el-form-item>
       <!-- <el-form-item label="上级栏目" prop="parentId" >
         <el-cascader
           :options="options"
            v-model="selectedOptions"
            @change="handleChange">
         </el-cascader>
      </el-form-item> -->
    	<!-- <el-form-item label="上级栏目" required>
        <el-tree :data="tree" 
         show-checkbox
         node-key="id"
         @check-change="handleCheckChange"
         ref="tree">
        </el-tree>
      </el-form-item> -->
      <el-form-item label="栏目路径" prop="channelPath" required>
        <el-input v-model="formData.channelPath"></el-input>
      </el-form-item>
      <el-form-item label="排列顺序" prop="priority" required>
        <el-input v-model="formData.priority" ></el-input>
      </el-form-item>
     <el-form-item label="是否有内容" prop="hasContent" required>
        <el-select v-model="formData.hasContent">
          <el-option v-for="(item, index) in ['是', '否']" :value="String(index+1)" :label="item" :key="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否显示" prop="isDisplay" required>
        <el-select v-model="formData.isDisplay">
          <el-option v-for="(item, index) in ['是', '否']" :value="String(index+1)" :label="item" :key="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="栏目名称" prop="columnName" required>
        <el-input v-model="formData.columnName" ></el-input>
      </el-form-item>
       <el-form-item label="外部地址" prop="linkUrl">
        <el-input v-model="formData.linkUrl"></el-input>
      </el-form-item>
       <el-form-item label="是否新页面打开" prop="isBlank" required>
        <el-select v-model="formData.isBlank">
          <el-option v-for="(item, index) in ['是', '否']" :value="String(index)" :label="item" :key="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="栏目前缀" prop="tplChannelPrefix" >
        <el-input v-model="formData.tplChannelPrefix" ></el-input>
      </el-form-item>
      <el-form-item label="内容模板" prop="roleName">
        <el-input v-model="formData.roleName"></el-input>
      </el-form-item>
      <el-form-item label="封面图片" prop="contentImg">
      	<div class="editImg" v-if="imgShow === 'edit'">
      		<img :src="imgSrc(formData.contentImg)" />
      	</div>
        <el-upload
				  :action="baseUrl()"
				  class="upload-demo"
				  list-type="picture-card"
          :data="dataObj"
				  accept="image/jpeg,image/gif,image/png,image/bmp"
				  :on-preview="handlePictureCardPreview"
				  :on-remove="handleRemove"
				  :on-change="handleChangeImg"
          :on-success="handleSuccess"
				  :auto-upload = "true"
          :on-error="handleError"
				  :drag="false"
				  >
				  <i class="el-icon-plus"></i>
				   <div slot="tip" class="el-upload__tip">建议尺寸：450*380</div>
				</el-upload>
				<el-dialog :visible.sync="dialogVisible" size="tiny">
				  <img width="100%" :src="dialogImageUrl" alt="">
				</el-dialog>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="submit('ruleForm')">确 定</el-button>
    </div>
  </div>
</template>

<script>
import { createColumn, editColumn, queryMenuColumn} from "@/services/program";
import { RequestError } from "@/services/errors";
import { mapActions } from "vuex";
import { imgSrcUrl } from "@/services/imgSrcUrl";
import AuthStorage from '@/services/storage.js'
export default {
  name: "edit-role",
  data () {
    return {
      options:[],
      tree:[],
      menus: [],
      list: [],
      parentdata:[],
      dataObj: { token: AuthStorage.token, key: '' },
      formData: {
        siteId: "",
        channelPath: "",
        hasContent: "",
        isDisplay: "",
        columnName: "",
        isBlank: "",
        contentImg:"",
        priority:""
      },
      menuInfo: [],
      imgShow:"",
      dialogImageUrl: '',
      dialogVisible: false,
      dialogFormVisible: false,
      dialogFormVisible: false,
      rules: {
        siteId: [{ required: true, message: "请输入站点id", trigger: "blur" }],
        channelPath: [{ required: true, message: "请输入栏目路径", trigger: "blur" }],
        hasContent: [{ required: true, message: "请选择是否有内容", trigger: "blur" }],
        isDisplay: [{ required: true, message: "请选择是否显示", trigger: "blur" }],
        columnName: [{ required: true, message: "请输入栏目名称", trigger: "blur" }],
        isBlank: [{ required: true, message: "请选择是否新页面打开", trigger: "blur" }],
        priority: [{ required: true, message: "请输入排列顺序", trigger: "blur" }]
      }
    }
  },

  props: {
    view: {
      type: String,
      default: "create"
    }
  },
  methods: {
    // ...mapActions(["setUserInfo"]),
    handleCheckChange(data, checked, indeterminate) {
        let myarr =this.$refs.tree.getCheckedNodes()
        this.formData.columnList = myarr;
    },
    async queryMenu(){
            let data = await queryMenuColumn();
            await this.$nextTick();
            this.tree = data.rootTrees;
            this.options = data.rootTrees;
      },
    closeDialog() {
      this.$emit("close");
    },
    baseUrl(){
      return "/ecshop/console/upload/uploadImg.do";
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleRemove(file, fileList) {
    },
    handleChangeImg(file,fileList){
      this.imgShow = ""
      // console.log(file.response.rspCode);
      // if(file.response.rspCode!="0000"){
      //     	this.$message.warning('上传图片失败');
      // }
    	  if(fileList.length > 1){
	    		this.$message.warning('当前限制选择 1个文件,多张图片覆盖第一张');
	    		var thisNode = document.getElementsByClassName("el-upload-list__item")[0];
	    		thisNode.parentNode.removeChild(thisNode);
	    	}
    	  var isJPG = ""
    	  if(file.raw.type === 'image/jpeg' || file.raw.type === 'image/png'){
    		  isJPG = true
    	  }else{
    		  isJPG = false
    	  }
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG/png 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
    },
    handleError(err, file, fileList){
        this.$message.error(err);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleSuccess(response, file, fileList){
      this.formData.contentImg = response.data;
    },
    imgSrc(data){
      	return imgSrcUrl() + data;
    },
    submit(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          try {
            if (this.view === "create") {
                   await createColumn(this.formData)
            } else {
                   await editColumn(this.formData)
            }
            this.dialogFormVisible = false;
            this.$emit("close", true);
            await this.queryMenu();
            this.$message({
              showClose: true,
              message: "提交成功",
              type: "success"
            });
           
          } catch (e) {
            if (e instanceof RequestError) {
              this.$alert(e.message, "提示", {
                type: "error",
                confirmButtonText: "确定"
              });
            } else {
              throw e;
            }
          }
        } else {
          return;
        }
      });
    }
  },
  created(){
    // this.queryMenu();
  },
  mounted() {}
};
</script>
<style>
.dialogWrapper {
  width: 76%;
}
.el-select {
  width: 100%;
}
.editImg{
	  overflow: hidden;
    background-color: #fff;
    border: 1px solid #c0ccda;
    border-radius: 6px;
    box-sizing: border-box;
    width: 148px;
    height: 148px;
    margin: 0 8px 8px 0;
    display: inline-block;
    float: left;
}
.editImg img{
	width: 100%;
	height: 100%;
}
.retu{
  margin-bottom: 20px;
}
</style>


